import pg from "pg";
import bcryptjs from "bcryptjs";
import path from "path";
import { fileURLToPath } from "url";
import dotenv from "dotenv";
import { dirname } from "path";
const { Pool } = pg;
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// 加载环境变量
dotenv.config();
// 创建数据库连接池
const pool = new Pool({
  user: String(process.env.PG_USER || "root"),
  password: String(process.env.PG_PASSWORD || "Letusdoit000"),
  host: String(process.env.PG_HOST || "localhost"),
  port: parseInt(process.env.PG_PORT || "5432", 10),
  database: String(process.env.PG_DATABASE || "app"),
});
// 生成的用户数量
const USER_COUNT = 50;
// 默认密码
const DEFAULT_PASSWORD = "123";
async function generateUsers() {
  try {
    console.log("开始生成用户数据...");
    // 测试数据库连接
    await pool.query("SELECT NOW()");
    // 查询现有最大用户ID
    const maxIdResult = await pool.query(`
      SELECT MAX(id) as max_id FROM users
    `);
    let lastId = 0;
    if (maxIdResult.rows.length > 0 && maxIdResult.rows[0].max_id) {
      lastId = parseInt(maxIdResult.rows[0].max_id, 10);
      // 重置序列到最大ID
      await pool.query(`
        SELECT setval('users_id_seq', $1, true)
      `, [lastId]);
      console.log(`检测到数据库最大用户ID: ${lastId}, 新用户将从ID ${lastId + 1} 开始创建`);
    } else {
      console.log("数据库中没有用户，将从ID 1开始创建");
      // 重置序列
      await pool.query(`
        SELECT setval('users_id_seq', 0, true)
      `);
    }
    // 查询现有最大用户编号（用于用户名）
    const maxUserResult = await pool.query(`
      SELECT username FROM users 
      WHERE username LIKE 'user%' 
      ORDER BY LENGTH(username) DESC, username DESC 
      LIMIT 1
    `);
    let usernameIndex = 1; 
    if (maxUserResult.rows.length > 0) {
      const maxUsername = maxUserResult.rows[0].username;
      // 从用户名中提取数字部分
      const match = maxUsername.match(/user(\d+)/);
      if (match && match[1]) {
        usernameIndex = parseInt(match[1], 10) + 1; // 从最大值的下一个开始
        console.log(`检测到最大用户名编号: ${match[1]}, 新用户名将从 user${usernameIndex} 开始`);
      }
    } else {
      console.log("未检测到user格式的用户名，将从user1开始创建");
    }
    // 生成用户
    let created = 0;
    for (let i = 0; i < USER_COUNT; i++) {
      const userNumber = usernameIndex + i;
      const username = `user${userNumber}`;
      const password = await bcryptjs.hash(DEFAULT_PASSWORD, 10);
      // 插入新用户
      await pool.query(
        "INSERT INTO users (username, password) VALUES ($1, $2)",
        [username, password]
      );
      created++;
    }
    
    // 输出结果统计
    console.log(`成功创建 ${created} 个新用户`);
    console.log(`新用户名范围: user${usernameIndex} 至 user${usernameIndex + USER_COUNT - 1}`);
    console.log(`ID从: ${lastId + 1} 增加至 ${lastId + created}`);
    console.log(`密码: ${DEFAULT_PASSWORD}`);
  } catch (error) {
    console.error("生成用户数据失败:", error.message);
  } finally {
    await pool.end();
    console.log("数据库连接已关闭");
  }
}
generateUsers();
